package com.company.pedidos.web.controller;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.hibernate.service.spi.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.multipart.MultipartFile;

import com.company.canonical.beans.JsonJTableClienteBean;
import com.company.canonical.beans.JsonJTableCorreoBean;
import com.company.canonical.beans.JsonJTableDocumentoBean;
import com.company.canonical.beans.JsonJTableNotaBean;
import com.company.canonical.beans.JsonJTableOptionBean;
import com.company.canonical.beans.JsonJTableTelefonoBean;
import com.company.pedidos.domain.Visita;
import com.company.pedidos.service.PedidosService;
import com.company.pedidos.web.command.ClienteCommand;
import com.company.pedidos.web.datatable.response.JtableJsonListResponse;
import com.google.gson.Gson;

@RequestMapping("/cliente")
@SessionAttributes("clienteId")
@Controller
public class ClienteController {

	private static final Logger logger = Logger
			.getLogger(ClienteController.class);

	@Autowired
	private PedidosService pedidosService;

	@Value("#{configuration['cliente.controller.target.path.file']}")
	private String targetPath;

	public ClienteController() {

	}

	@ModelAttribute("cliente")
	public ClienteCommand crearClienteModel() {
		logger.debug("creating @ModelAttribute object");
		ClienteCommand command = new ClienteCommand();
		return command;
	}

	/**
	 * 
	 * @return
	 */
	@RequestMapping(value = "/mostrar", method = RequestMethod.GET)
	public String inicioConsultaCliente(ModelMap modelMap) {
		List<JsonJTableOptionBean> listaTipoDocumento = null;
		try {
			listaTipoDocumento = pedidosService.listarTipoDocumento();
			modelMap.addAttribute("tipoDocumento", listaTipoDocumento);
		} catch (ServiceException e) {
			e.printStackTrace();
		}
		return "cliente/consultaCliente";
	}

	/**
	 * @return
	 */
	@RequestMapping(value = "/buscar", method = RequestMethod.POST)
	@ResponseBody
	public JtableJsonListResponse<JsonJTableClienteBean> buscarCliente(
			@ModelAttribute(value = "cliente") ClienteCommand cliente,
			@RequestParam(required = false, value = "jtStartIndex") int jtStartIndex,
			@RequestParam(required = false, value = "jtPageSize") int jtPageSize) {
		JtableJsonListResponse<JsonJTableClienteBean> jsonString;
		List<JsonJTableClienteBean> clienteList;
		try {
			Long clienteCount = pedidosService.buscarClienteCount(
					cliente.getTipoDocumento(), cliente.getNumeroDocumento(),
					cliente.getNombreCliente());
			clienteList = pedidosService.buscarCliente(
					cliente.getTipoDocumento(), cliente.getNumeroDocumento(),
					cliente.getNombreCliente(), jtStartIndex, jtPageSize);
			jsonString = new JtableJsonListResponse<JsonJTableClienteBean>(
					"OK", clienteList, clienteCount.intValue());
		} catch (Exception e) {
			jsonString = new JtableJsonListResponse<JsonJTableClienteBean>(
					"ERROR", e.getMessage());
		}
		return jsonString;
	}

	@RequestMapping(value = "/detalle", params = {"clienteId"}, method = RequestMethod.GET)
	public String mostrarDetalleCliente(ModelMap modelMap,
			@RequestParam("clienteId") String clienteId) {
		logger.debug("Parametro: " + clienteId);
		modelMap.clear();
		modelMap.addAttribute("clienteId", clienteId);
		return "cliente/detalle";
	}
	
	@RequestMapping(value = "/detalle/nota", method = RequestMethod.GET)
	public String mostrarDetalleNota(@RequestParam("clienteId") String clienteId,ModelMap modelMap) {
		logger.debug("clienteId: "+ clienteId);
		return "cliente/notaCliente";
	}

	@RequestMapping(value = "/detalle/nota", method = RequestMethod.POST)
	@ResponseBody
	public JtableJsonListResponse<JsonJTableNotaBean> mostrarNota(
			@RequestParam("clienteId") String clienteId,
			@RequestParam("jtStartIndex") int jtStartIndex,
			@RequestParam("jtPageSize") int jtPageSize) {
		JtableJsonListResponse<JsonJTableNotaBean> jsonString;
		List<JsonJTableNotaBean> listaNota;
		logger.debug("Parametro: " + clienteId);
		try {
			Long count = pedidosService.listaNotaClienteCount(clienteId);
			listaNota = pedidosService.listaNotaCliente(clienteId, jtStartIndex, jtPageSize);
			jsonString = new JtableJsonListResponse<JsonJTableNotaBean>("OK",
					listaNota, count.intValue());
		} catch (Exception e) {
			jsonString = new JtableJsonListResponse<JsonJTableNotaBean>(
					"ERROR", e.getMessage());
		}
		logger.debug("JSON: " + jsonString);
		return jsonString;
	}

	@RequestMapping(value = "/detalle/correo", method = RequestMethod.POST)
	@ResponseBody
	public JtableJsonListResponse<JsonJTableCorreoBean> mostrarCorreo(
			@RequestParam("clienteId") String clienteId) {
		JtableJsonListResponse<JsonJTableCorreoBean> jsonString;
		List<JsonJTableCorreoBean> listaCorreo;
		logger.debug("Parametro: " + clienteId);
		try {
			listaCorreo = pedidosService.listaCorreoCliente(clienteId);
			jsonString = new JtableJsonListResponse<JsonJTableCorreoBean>("OK",
					listaCorreo, listaCorreo.size());
		} catch (Exception e) {
			jsonString = new JtableJsonListResponse<JsonJTableCorreoBean>(
					"ERROR", e.getMessage());
		}
		return jsonString;
	}

	@RequestMapping(value = "/detalle/telefono", method = RequestMethod.POST)
	@ResponseBody
	public JtableJsonListResponse<JsonJTableTelefonoBean> mostrarTelefono(
			@RequestParam("clienteId") String clienteId) {
		JtableJsonListResponse<JsonJTableTelefonoBean> jsonString;
		List<JsonJTableTelefonoBean> listaTelefono;
		logger.debug("Parametro: " + clienteId);
		try {
			listaTelefono = pedidosService.listarTelefonoCliente(clienteId);
			jsonString = new JtableJsonListResponse<JsonJTableTelefonoBean>(
					"OK", listaTelefono, listaTelefono.size());
		} catch (Exception e) {
			jsonString = new JtableJsonListResponse<JsonJTableTelefonoBean>(
					"ERROR", e.getMessage());
			logger.debug("Error " + jsonString);
		}
		return jsonString;
	}

	@RequestMapping(value = "/detalle/documentoCobrar", method = RequestMethod.POST)
	@ResponseBody
	public JtableJsonListResponse<JsonJTableDocumentoBean> mostrarDocumentoCobrar(
			@RequestParam String clienteId,
			@RequestParam("jtStartIndex") int jtStartIndex,
			@RequestParam("jtPageSize") int jtPageSize) {
		JtableJsonListResponse<JsonJTableDocumentoBean> jsonString;
		List<JsonJTableDocumentoBean> listaDocumento;
		try {
			Long expenseCount = pedidosService
					.listaDocumentoCobrarClienteCount(clienteId);
			listaDocumento = pedidosService.listaDocumentoCobrarCliente(
					clienteId, jtStartIndex, jtPageSize);
			jsonString = new JtableJsonListResponse<JsonJTableDocumentoBean>(
					"OK", listaDocumento, expenseCount.intValue());
		} catch (Exception e) {
			jsonString = new JtableJsonListResponse<JsonJTableDocumentoBean>(
					"ERROR", e.getMessage());
		}
		return jsonString;
	}

	@RequestMapping(value = "/verRegistro", method = RequestMethod.GET)
	public String inicioVisitaCliente(ModelMap modelMap) {
		modelMap.addAttribute("usuarioId", 123456);
		return "cliente/registroCliente";
	}

	@RequestMapping(value = "/visita/{id}", method = RequestMethod.GET)
	public @ResponseBody
	String loadResourceVacation(@PathVariable int id,
			HttpServletResponse response) throws Exception {
		logger.debug("idCliente : " + id);
		List<Visita> listaVisita = pedidosService.obtenerVisitaCliente(id);
		logger.debug("ListaVisita: " + listaVisita.size());
		String json = new Gson().toJson(listaVisita);
		logger.debug("JsonData: " + json);
		// Write JSON string.
		response.setContentType("application/json");
		response.setCharacterEncoding("UTF-8");
		return json;
	}

	/**
	 * 
	 * @return
	 */
	@RequestMapping(value = "/registro/visita", method = RequestMethod.POST)
	public String registrarVisita() {

		return "cliente/registroCliente";
	}

	/**
	 * 
	 * @return
	 */
	@RequestMapping(value = "/upload", method = RequestMethod.GET)
	public String uploadInit() {
		return "uploadCliente";
	}

	/**
	 * 
	 * @param name
	 * @param file
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/upload", method = RequestMethod.POST)
	public String handleFileUpload(@RequestParam("file") MultipartFile file)
			throws Exception {

		if (!file.isEmpty()) {

			logger.debug(" the file " + file.getOriginalFilename()
					+ "was uploaded");
			byte[] bytes = file.getBytes();
			BufferedOutputStream stream = new BufferedOutputStream(
					new FileOutputStream(new File(targetPath
							+ file.getOriginalFilename())));
			stream.write(bytes);
			stream.close();
			return "uploadCliente";

		}

		return "";
	}

}
